package com.lcl.jarvis.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lcl.jarvis.exception.BizException;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * JWT工具类
 *
 * @vesion 1.0
 * @date 2018/7/16 22:29
 * @since jdk1.8
 */
public class JwtUtils {
    private static final String SECRET = "jarvis_secret";
    private static final long EXPIRATION_TIME = 3600000; // 1 hours
    private static final String ISSUER = "jarvis_issuer";

    public static String createJWT(String subject, String username) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            Date expirationDate = new Date(System.currentTimeMillis() + EXPIRATION_TIME);

            return JWT.create()
                    .withSubject(subject)
                    .withClaim("username", username) // 添加用户名到JWT 中
                    .withExpiresAt(expirationDate)
                    .withIssuer(ISSUER)
                    .sign(algorithm);
        } catch (JWTCreationException exception) {
            // 处理创建JWT 异常
            return null;
        }
    }

    public static String verifyAndDecodeJWT(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            DecodedJWT jwt = JWT.require(algorithm)
                    .withIssuer(ISSUER)
                    .build()
                    .verify(token);
            return jwt.getClaim("username").asString(); // 解析JWT，提取用户名
        } catch (JWTDecodeException exception){
            // 处理JWT 解析异常
            return null;
        }
    }


}
